/**
 * @projectDescription JavaScript for wikigateway.xml
 * @link http://code.google.com/p/wikignpi
 * @author Bruno Santos
 * @license MIT License <http://www.opensource.org/licenses/mit-license.php>
 *
 * Usage:
 *   Shown here: http://code.google.com/p/wikignpi/wiki/GadgetThatWiki
 */

var my_log = function(text){};
if(window.console && window.console.log){
   my_log = window.console.log;
}

// Get userprefs
var prefs = new gadgets.Prefs();

gnpi_projectname = prefs.getString("projectname");
gnpi_subversion = prefs.getString("subversion");
gnpi_wikiname = prefs.getString("wikiname");
gnpi_autoresize = prefs.getBool("autoresize");
gnpi_disableWarnings = prefs.getBool("disableWarnings");
gnpi_wikiBaseURL = prefs.getString("wikiBaseURL");
gnpi_openURLSInNewWindow = prefs.getBool("openURLSInNewWindow");
gnpi_showLabels = prefs.getBool("showLabels");
gnpi_showSummary = prefs.getBool("showSummary");
gnpi_showFileNameAsTitle = prefs.getBool("showFileName");
gnpi_refreshRate = prefs.getInt("cachedTime");
gnpi_hideComments = prefs.getBool("hideComments");
gnpi_showGadgets = prefs.getBool("showGadgets");
gnpi_showVideos = prefs.getBool("showVideos");
gnpi_language = prefs.getString("language");
gnpi_showLanguages = prefs.getBool("showLanguages");
gnpi_plugins = prefs.getString("plugins");

gnpi_monitor_height = -1;
gnpi_languagesAvailable = "";
gnpi_pre_plugins = {};
gnpi_post_plugins = {};
gnpi_count_injected_plugins = 0;

//setup the base location
gnpi_baselocation="http://";
if(gnpi_subversion.indexOf("hg")>=0) {
  gnpi_baselocation += "wiki." + gnpi_projectname + ".googlecode.com";
} else { /* gnpi_subversion.indexOf("svn")>=0 */
  gnpi_baselocation += gnpi_projectname + ".googlecode.com";
}

//setup the css
if(gnpi_subversion.indexOf("hg")>=0) {
  $('head').append('<link href="'+ gnpi_baselocation +'/hg/gadgets/ph_core.min.css" rel="stylesheet" type="text/css"></link>');
  $('head').append('<link href="'+ gnpi_baselocation +'/hg/gadgets/ph_detail.min.css" rel="stylesheet" type="text/css"></link>');
  if($.browser.msie) {
    $('head').append('<link type="text/css" rel="stylesheet" href="'+ gnpi_baselocation +'/hg/gadgets/d_ie.css" >');
  }
} else { /* gnpi_subversion.indexOf("svn")>=0 */
  $('head').append('<link href="'+ gnpi_baselocation +'/svn/wiki/gadgets/ph_core.min.css" rel="stylesheet" type="text/css"></link>');
  $('head').append('<link href="'+ gnpi_baselocation +'/svn/wiki/gadgets/ph_detail.min.css" rel="stylesheet" type="text/css"></link>');
  if($.browser.msie) {
    $('head').append('<link type="text/css" rel="stylesheet" href="'+ gnpi_baselocation +'/svn/wiki/gadgets/d_ie.css" >');
  }
}


/* ------------------------------------------------------------------------ */
/*                               Functions                                  */

function generateWikiURL()
{
  gnpi_url="";
  if(gnpi_subversion.indexOf("hg")>=0) {
    gnpi_url += gnpi_baselocation + "/hg/";
  } else { /* gnpi_subversion.indexOf("svn")>=0 */
    gnpi_url += gnpi_baselocation + "/svn/wiki/";
  }
  if(gnpi_language.length>0 && useThatLanguage()) {
    gnpi_url += gnpi_language + "/";
  }
  gnpi_url+=gnpi_wikiname+".wiki";
};

function useThatLanguage() {
  var unlistedLangs = gnpi_languagesAvailable.length == 0, noLanguageSpecified = gnpi_language.length == 0;
  var canUse = unlistedLangs && !noLanguageSpecified;

  if(noLanguageSpecified) {
    canUse = false;
  } else if(!unlistedLangs && gnpi_languagesAvailable.indexOf(gnpi_language)<=0) {
    canUse = false;
  } else if(!unlistedLangs) {
    canUse = true;
  }

  return canUse;
};

function generateLangsDefaultFileURL() {
  gnpi_url="";
  if(gnpi_subversion.indexOf("hg")>=0) {
    gnpi_url += gnpi_baselocation + "/hg/";
  } else { /* gnpi_subversion.indexOf("svn")>=0 */
    gnpi_url += gnpi_baselocation + "/svn/wiki/";
  }
  gnpi_url+="languages.lst";
};


function makeCachedRequest(url, callback, params, refreshInterval) {
  var ts = new Date().getTime();
  var sep = "?";
  if (refreshInterval && refreshInterval > 0) {
    ts = Math.floor(ts / (refreshInterval * 1000));
  }
  if (url.indexOf("?") > -1) {
    sep = "&";
  }
  url = [ url, sep, "nocache=", ts ].join("");
  gadgets.io.makeRequest(url, callback, params);
};

function getLangs() {
  var params = {};

  generateLangsDefaultFileURL();

  params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
  if(gnpi_refreshRate>-1) {
    makeCachedRequest(gnpi_url, armLanguages, params, gnpi_refreshRate);
  }else{
    gadgets.io.makeRequest(gnpi_url, armLanguages, params);
  }
};

function armLanguages(data) {
  gnpi_languagesAvailable = data.text;

  //Now got get that wiki!
  getWiki();
};

function generateLangsHTMLLine() {
  var htmlLine = '', defaultLang = gnpi_language;
  if(gnpi_showLanguages && gnpi_languagesAvailable.length>0) {
    var languagesAvailable = gnpi_languagesAvailable.split(',');
    var j, languageLinks = generateLanguageLinks(languagesAvailable);

    if(defaultLang.length == 0) {
      defaultLang = languagesAvailable[0];
    }

    for(j in languagesAvailable) {
      if(htmlLine.length>0) htmlLine += ', ';
      if(languagesAvailable[j] == defaultLang) {
        htmlLine += '<b>' + defaultLang + '</b>';
      } else {
        htmlLine += '<a title="' + languagesAvailable[j] + '" href="' + languageLinks[j] + '">' + languagesAvailable[j] + '</a>';
      }
    }
  }
  return htmlLine;
};

function generateLanguageLinks(langs) {
  var j, langLinks = new Array(langs.length);
  var originalURL = window.location.href;
  var hashPos = originalURL.indexOf('#'), questionPos = originalURL.indexOf('?');
  var hashText = '';
  if(hashPos>0) {
    hashText = originalURL.substr(hashPos+1);
    originalURL = originalURL.substr(0,hashPos);
  }

  //find if the up_language option is already included
  if(originalURL.indexOf('up_language=')<0) {
    //have to inject this option into the string
    var parentPos = originalURL.indexOf('parent=');
    if(parentPos < 0) {
      originalURL += 'up_language=';
    }
  }
  var rxlang=/(up_language=)([a-zA-Z]+)([&$])?/;
  var ma = rxlang.exec(originalURL);
  var toRep = '';
  if(ma[3] == undefined) ma[3] = '';

  for(j in langs) {
    toRep = ma[1] + langs[j] + ma[3];
    langLinks[j] = originalURL.replace(ma[0], toRep);
    if(hashText.length>0) langLinks[j] += '#' + hashText;
  }

  return langLinks;
};

function getWiki() {
  var params = {};

  generateWikiURL();

  params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
  if(gnpi_refreshRate>-1) {
    makeCachedRequest(gnpi_url, postwiki, params, gnpi_refreshRate);
  }else{
    gadgets.io.makeRequest(gnpi_url, postwiki, params);
  }
};

function postwiki(data)
{
  data = GNPI_runPrePlugins(data.text);
  var g = new GoogleCodeWikiParser(gnpi_showSummary,gnpi_showLabels);
  g.options.disableWarnings=gnpi_disableWarnings;
  g.options.wikiBaseURL=gnpi_wikiBaseURL;
  g.options.openURLSInNewWindow=gnpi_openURLSInNewWindow;
  g.options.hideComments = gnpi_hideComments;
  g.options.showGadgets = gnpi_showGadgets;
  g.options.showVideos = gnpi_showVideos;
  g.options.injectAfterLabels = generateLangsHTMLLine();

  var html = g.parse( data );
  if(gnpi_showFileNameAsTitle) html = "<h1>"+gnpi_wikiname+"</h1>" + html;

  $('#wikicontent')[0].innerHTML=html;
  html="";

  GNPI_runPostPlugins($('#wikicontent'));

  if(gnpi_autoresize) $(resizeMonitor);
};

function resizeMonitor()
{
  if ($('body').outerHeight( true ) != gnpi_monitor_height) {
    gnpi_monitor_height=$('body').outerHeight( true );
    gadgets.window.adjustHeight();
  }
  setTimeout(resizeMonitor,1000);
};

/* This function is called by the plug-in itself! */
function GNPI_registerPrePlugin(plugin_name, plugin_function)
{
  gnpi_pre_plugins[plugin_name] = plugin_function;
};

/* This function is called by the plug-in itself! */
function GNPI_registerPostPlugin(plugin_name, plugin_function)
{
  gnpi_post_plugins[plugin_name] = plugin_function;
};

/* NOTE: plugin_options is already an array with unparsed options */
function processPluginOptions(plugin_name, plugin_options)
{
    for(var j=0; j<plugin_options.length; j++)
    {
      if(plugin_options[j].length>0)
      {
        eval('___' + plugin_name + '_' + unescape(plugin_options[j]) + ';');
      }
    }
};

function generateGNPIPluginURL(plugin_name)
{
  var url="";
  if(gnpi_subversion.indexOf("hg")>=0) {
    url += gnpi_baselocation + "/hg/gadgets/plugins/";
  } else { /* gnpi_subversion.indexOf("svn")>=0 */
    url += gnpi_baselocation + "/svn/wiki/gadgets/plugins/";
  }
  url += plugin_name + ".js";
  return url;
};

function injectPluginScriptIntoHead(plugin_url)
{
  var script=window.document.createElement('script');
  script.src=plugin_url;
  var head=window.document.getElementsByTagName('head')[0],
  done=false;
  // Attach handlers for all browsers
  script.onload=script.onreadystatechange = function(){
    if ( !done && (!this.readyState
        || this.readyState == 'loaded'
        || this.readyState == 'complete') ) {
        done=true;
        script.onload = script.onreadystatechange = null;
        head.removeChild(script);
    }
  };
  head.appendChild(script);
};

function loadGNPIPlugins()
{
  gnpi_plugins = unescape(gnpi_plugins);
  var j, plugin_list = gnpi_plugins.split('|');

  for(j in plugin_list) {
    if(plugin_list[j].length>0) {
      var plugin_info = plugin_list[j].split('?');
      var plugin_name = plugin_info[0];
      if(plugin_info.length>1) {
        processPluginOptions(plugin_name, plugin_info[1].split('&'));
      }
      injectPluginScriptIntoHead(generateGNPIPluginURL(plugin_name));
      gnpi_count_injected_plugins++;
    }
  }
};


function GNPI_runPrePlugins(wikitext)
{
  var j;
  for(j in gnpi_pre_plugins) {
    wikitext = gnpi_pre_plugins[j](wikitext);
  }
  return wikitext;
};

function GNPI_runPostPlugins(jQwikicontent)
{
  var j;
  for(j in gnpi_post_plugins) {
    gnpi_post_plugins[j](jQwikicontent);
  }
};

/*                        End of Functions                                  */
/* ------------------------------------------------------------------------ */

loadGNPIPlugins();

if(gnpi_language.length==0) {
  gadgets.util.registerOnLoadHandler(getWiki);
} else {
  gadgets.util.registerOnLoadHandler(getLangs);
}
